package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
杨威
2021/10/4
19:58
*/
public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        String invoke = null;
        try {
            Method method1 = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            invoke = (String)method1.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        if(invoke==null){
            return;
        }
        if(invoke.startsWith("forward:")){
            String substring = invoke.substring(invoke.indexOf(":") + 1);
            req.getRequestDispatcher(substring).forward(req,resp);
        }else if(invoke.startsWith("redirect:")){
            String substring = invoke.substring(invoke.indexOf(":") + 1);
            resp.sendRedirect(req.getContextPath()+substring);
        }else{
            resp.getWriter().println(invoke);
        }
    }
}
